package com.allen.flink.batch.sql;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.java.StreamTableEnvironment;

/**
 * 功能: 流SQL示例
 *
 * @date: 2020-03-25 15:03
 * @author: Allen
 * @version: 0.0.4-snapshot
 * @Email: allenZyhang@163.com
 * @since: JDK 1.8
 **/
public class StreamSQL {
    
    public static void main(String[] args) throws Exception {
        //获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        
        //创建一个TableEnvironment
        StreamTableEnvironment streamTabEnv = StreamTableEnvironment.create(env);
        
        //读取数据源
        DataStream<String> ds = env.readTextFile("D:/Flink/user.txt");
        
        //数据转换
        DataStream<Tuple2<String, String>> dsMap = ds.map(new MapFunction<String, Tuple2<String, String>>() {
            @Override
            public Tuple2<String, String> map(final String s) throws Exception {
                String[] arr = s.split(",");
                return new Tuple2<>(arr[0], arr[1]);
            }
        });
        
        //DataStream 转换为Table
        Table table = streamTabEnv.fromDataStream(dsMap, "uid,name");
        
        //注册为一个表
        streamTabEnv.registerTable("user1", table);
        
        Table table2 = streamTabEnv.sqlQuery("select * from user1").select("name");
        
        //表转流
        DataStream<String> ds2 = streamTabEnv.toAppendStream(table2, String.class);
        
        //打印
        ds2.print();
        
        env.execute("Flink Stream SQLAPI");
    }
}
